package conqueror.com.camerarecord;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.util.Log;
import android.view.SurfaceHolder;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import conqueror.com.camerarecord.utils.FileUtil;


public class AboutCamera {
    private String TAG = "RecordService";
    public Camera mCameraFront;
    private File outputMediaFile;

    public AboutCamera(int whichCamera) {
        this.outputMediaFile = new FileUtil().getOutputMediaFile();
        this.mCameraFront = openCamera(whichCamera);
    }


    /**
     * 预览窗口
     *
     * @return （true表成功，false表失败）
     */
    public Boolean startFrontPreview(SurfaceHolder surfaceHolderFront) {
        Log.e(TAG, Camera.getNumberOfCameras() + "");
        //打开相机（可选择）
//        mCameraFront = openCamera(Camera.CameraInfo.CAMERA_FACING_BACK);
//        mCameraFront = openCamera(witchCamera);
        Log.e(TAG, "==============" + mCameraFront);
        Camera.Parameters parametersFront = mCameraFront.getParameters();

        parametersFront.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
//      parametersFront.setPreviewSize(1280, 720);
        parametersFront.setJpegQuality(100);//图片质量
        mCameraFront.setParameters(parametersFront);
        try {
            mCameraFront.setPreviewDisplay(surfaceHolderFront);
            mCameraFront.setDisplayOrientation(90);//可修改角度
            mCameraFront.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 打开相机
     *
     * @param i（前后摄像头）
     * @return camera
     */
    private Camera openCamera(int i) {
        Camera cam = null;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();

        for (int camIdx = 0, cameraCount = Camera.getNumberOfCameras(); camIdx < cameraCount; camIdx++) {
            Camera.getCameraInfo(camIdx, cameraInfo);
            if (cameraInfo.facing == i) {
                try {
                    cam = Camera.open(camIdx);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    Log.e(TAG, "---------------openCamera fail");
                }
            }
        }
        return cam;
    }


    public void getPreViewImage() {
        mCameraFront.setOneShotPreviewCallback(new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] data, Camera camera) {
                Camera.Size size = camera.getParameters().getPreviewSize();
                Log.e(TAG, camera.getParameters().getPreviewFormat() + "");
                try {
                    YuvImage image = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);
                    if (image != null) {
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        image.compressToJpeg(new Rect(0, 0, size.width, size.height), 90, stream);

                        Bitmap bmp = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
                        //**********************
                        //因为图片会放生旋转，因此要对图片进行旋转到和手机在一个方向上
                        // rotateMyBitmap(bmp);
                        //**********************************
                        Log.e(TAG, "onPreviewFrame");
                        saveBitmap(bmp);
                        stream.close();
                    }
                } catch (Exception ex) {
                    Log.e("Sys", "Error:" + ex.getMessage());
                }
            }


        });
    }


    /**
     * 图片的保存
     *
     * @param bm
     */
    public void saveBitmap(Bitmap bm) {
        Log.e(TAG, "保存图片");
        File f = outputMediaFile;

        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i(TAG, "已经保存");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 拍照
     */
    public void takePhonePicture() {
        mCameraFront.takePicture(shutterCallback, null, jpegCallback);
    }

    private ToneGenerator tone;

    private Camera.ShutterCallback shutterCallback = new Camera.ShutterCallback() {
        @Override
        public void onShutter() {
            Log.i(TAG, "shutterCallback");
            if (tone == null)
                //发出提示用户的声音
                tone = new ToneGenerator(AudioManager.STREAM_MUSIC, ToneGenerator.MAX_VOLUME);
            tone.startTone(ToneGenerator.TONE_PROP_BEEP2);
        }
    };

    private Camera.PictureCallback jpegCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFile = outputMediaFile;
            if (pictureFile == null) {
                Log.d(TAG, "Error creating media file, check storage permissions: ");
            }
            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Log.d(TAG, "File not found: " + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                Log.d(TAG, "Error accessing file: " + e.getMessage());
            }
            mCameraFront.startPreview();
        }
    };
}
